﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MyServer.Common;
using FrameWork.Output;

namespace ScreenMonitor.ServerLib.OutputCollector
{
    /// <summary>
    /// 为数据操作器提供输出采集
    /// </summary>
    public abstract class QueueOperateItemOutputCollector:LogableOutputCollector
    {
        private QueueOperateItemBase Oper;

        public override void Start()
        {
            if (IsStarted)
                return;
            Oper.AfterOperateData += Oper_AfterOperateData;
            Oper.ErrorCatched += Oper_ErrorCatched;
            base.Start();
            IsStarted = true;
        }


        void Oper_ErrorCatched(object sender,ErrorCatchedEventArgs e)
        {
            string Detail="操作数据时发生错误："+
                e.Exception.Message+"\r\n"+
                "出错对象："+"\r\n" + 
                e.Exception.Source+"\r\n"+
                "调用堆栈：" + "\r\n" + 
                e.Exception.StackTrace;
            OutputItem i = new OutputItem(OutputType.Error, "操作数据发生错误：" + e.Exception.Message, e, Detail);
            OutputEventArgs e1=new OutputEventArgs(i);
            OnNewOutputGet(this, e1);
        }

        void Oper_AfterOperateData(object sender, DataAfterOperateEventArgs e)
        {
            OutputItem i=null;
            if (!e.IsSucceed)
                i = new OutputItem(OutputType.Error, "数据操作失败！", e.OperateData, "数据操作失败！");
            if (e.Canceled)
                i = new OutputItem(OutputType.Waring, "数据操作被取消！", e.OperateData, "数据操作已被取消！");
            if (i == null)
                return;
            OutputEventArgs e1 = new OutputEventArgs(i);
            OnNewOutputGet(this, e1);
        }

        public override void Stop()
        {
            if (!IsStarted)
                return;
            Oper.AfterOperateData -= Oper_AfterOperateData;
            Oper.ErrorCatched -= Oper_ErrorCatched;
            base.Stop();
            IsStarted = false;
        }

        /// <summary>
        /// 通过指定的发送器构造输出采集器实例
        /// </summary>
        /// <param name="Oper"></param>
        public QueueOperateItemOutputCollector(QueueOperateItemBase Oper):base(Oper)
        {
            this.Oper = Oper;
        }

    }
}
